<?php
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
    exit('Access Denied');
}

$kami_buy_type = C::t('#erling_kami_buy#er_kami_buy_type')->fetch_all();
$kami_buy_type = $kami_buy_type['data'];
$kami_buy = C::t('#erling_kami_buy#er_kami_buy');
$configs = C::t('#erling_kami_buy#er_kami_buy_config')->fetch_by_keys([
    'kami_expire_time','kami_length','kami_char_type','kami_format','kami_exclude_similar','kami_prefix'
]);
if(!empty($configs['kami_expire_time']['value'])) {
    $configs['kami_expire_time']['value'] = time() + ($configs['kami_expire_time']['value'] * 86400);
}
// 处理表单提交
if(submitcheck('submit')) {
    if(!submitcheck('submit', 1)) {
        cpmsg('表单验证失败，请刷新后重试', '', 'error');
    }

    $form_data = [];
    $form_action = $_POST['form_action'];

    if($form_action === 'manual') {
        // 手动添加
        $kami_delimiter = $_POST['kami_delimiter'];
        $manual_kami_textarea = $_POST['manual_kami_textarea'];
        if(empty($kami_delimiter)) {
            $kami_list = [trim($manual_kami_textarea)];
        } else {
            $kami_list = explode($kami_delimiter, $manual_kami_textarea);
            $kami_list = array_map('trim', $kami_list);
        }
        
        $kami_list = array_filter($kami_list);
        
        // 验证卡密列表不能为空
        if(empty($kami_list)) {
            cpmsg('卡密列表不能为空', '', 'error');
        }

        // 检查卡密列表自身是否有重复
        $unique_kamis = array_unique($kami_list);
        if(count($kami_list) !== count($unique_kamis)) {
            $duplicates = array_diff_assoc($kami_list, $unique_kamis);
            cpmsg('您输入的卡密列表中存在重复项：'.implode(', ', array_unique($duplicates)), '', 'error');
            exit;
        }

        // 检查卡密是否已存在
        $existing_kamis = $kami_buy->fetch_all_by_kami_keys($kami_list);
        $duplicates = array_intersect($kami_list, array_column($existing_kamis, 'kami_key'));
        
        if(!empty($duplicates)) {
            cpmsg('以下卡密已存在：'.implode(', ', $duplicates), '', 'error');
            exit;
        }
    } else {
        // 自动生成
        $kami_count = $_POST['kami_count']?? 1 ;
        $kami_length = $_POST['kami_length']?? 12;
        $kami_char_type = $_POST['kami_char_type'] ?? ['1','1'];// 第0号为1:数字 第1号为1:小写字母 第2号为1:大写字母 第3号为1:特殊字符
        $kami_format = $_POST['kami_format'];// 存在时将X替换为随机字符，不使用kami_length
        $kami_exclude_similar = $_POST['kami_exclude_similar'];//是否排除相似字符
        $kami_prefix = $_POST['kami_prefix'];//存在时加入前缀，不纳入长度范围

        $kami_list = [];
        $chars = '';
        $max_attempts = 10;//最大尝试次数
        $attempts = 0;//当前尝试次数
        
        // 构建字符池
        if($kami_char_type[0] == '1') $chars .= '0123456789';
        if($kami_char_type[1] == '1') $chars .= 'abcdefghijklmnopqrstuvwxyz';
        if($kami_char_type[2] == '1') $chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        if($kami_char_type[3] == '1') $chars .= '!@#$%^&*()';
        
        // 排除相似字符
        if($kami_exclude_similar) {
            $chars = str_replace(str_split($kami_exclude_similar), '', $chars);
        }
        
        // 生成卡密
        while(count($kami_list) < $kami_count && $attempts < $max_attempts) {
            $attempts++;
            $current_kami = '';
            
            if($kami_format) {
                // 使用格式模板
                $current_kami = ''; 
                $format_chars = str_split($kami_format);
                foreach($format_chars as $char) {
                    if($char === 'X') {
                        $current_kami .= $chars[rand(0, strlen($chars) - 1)];
                    } else {
                        $current_kami .= $char;
                    }
                }
            } else {
                // 随机生成指定长度
                for($j = 0; $j < $kami_length; $j++) {
                    $current_kami .= $chars[rand(0, strlen($chars) - 1)];
                }
            }
            
            // 添加前缀
            if($kami_prefix) {
                $current_kami = $kami_prefix . $current_kami;
            }
            
            // 检查是否重复
            if(!in_array($current_kami, $kami_list)) {
                // 检查数据库是否已存在
                $existing = $kami_buy->fetch_all_by_kami_keys([$current_kami]);
                if(empty($existing)) {
                    $kami_list[] = $current_kami;
                    $attempts = 0; // 重置尝试次数计数器
                }
            }
        }
        
        if(count($kami_list) < $kami_count) {
            cpmsg('生成失败，重复卡密过多（尝试'.$attempts.'次）。已生成 '.count($kami_list).' 个卡密。建议增加长度或增加字符类型包含', '', 'error');
            exit;
        }
    }

    if(empty($kami_list)) {
        cpmsg('生成失败', '', 'error');
        exit;
    }

    if(empty($_POST['kami_type'])) {
        cpmsg('请选择卡密分类', '', 'error');
        exit;
    }

    $expire_time = null;
    if(!empty($_POST['kami_expire_time'])) {
        $expire_time =strtotime($_POST['kami_expire_time']);
    }
    foreach ($kami_list as $kami) {
        $form_data[] = [
            'kami_key' => $kami,
            'kami_type' => $_POST['kami_type'],
            'expire_time' => $expire_time,
            'create_time' => $_G['timestamp'],
            'update_time' => $_G['timestamp'],
        ];
    }

    $kami_buy->insert_batch($form_data);
    cpmsg('生成成功', 'action=plugins&operation=config&do=128&identifier=erling_kami_buy&pmod=admin_kami_buy_create', 'succeed');
    exit;
}

// 积分类型
$extcredits_array = DB::fetch_all("SELECT * FROM %t WHERE skey LIKE %s", array('common_setting', 'extcredits%'));
if ($extcredits_array && isset($extcredits_array[0]['svalue'])) {
    $extcredits_data = unserialize($extcredits_array[0]['svalue']);
} else {
    $extcredits_data = [];
}

include template('erling_kami_buy:admin_kami_buy_create');
